package juc.thread.secuity;

import java.util.UUID;

/*
* 转账案例
* */
public class Test4 {

    public static void main(String[] args) {
        Account account1 = new Account(10000);
        Account account2 = new Account(10000);
        UUID uuid = UUID.randomUUID();//产生一个交易号 用来作为锁标识
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                synchronized (uuid) {
                    account1.transfer(10, account2);
                }
            }
        }, "account1");
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                synchronized (uuid) {
                    account2.transfer(10, account1);
                }
            }
        }, "account2");
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("总金额："+(account1.getBalance()+account2.getBalance()));
    }

  static class Account{
      private int balance;

      public Account(int money) {
          this.balance = money;
      }

      public int getBalance() {
          return balance;
      }

      public void setBalance(int balance) {
          this.balance = balance;
      }
      public  boolean transfer(int money,Account account){
//             synchronized (Account.class) {
                 if (balance >= money) {
                     balance -= money;
                     account.setBalance(account.getBalance() + money);
                     return true;
                 } else {
                     return false;
                 }
//             }
      }
  }
}
